<template>
  <div class="order-container">
    <!-- 添加返回按钮 -->
    <div class="header-with-back">
      <div class="back-button" @click="handleBack">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path fill="currentColor" d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"/>
        </svg>
      </div>
      <h3 class="page-title">卖出的商品</h3>
    </div>
    <div class="search-bar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索卖出商品名称"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          size="small"
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch" size="small" />
        </template>
      </el-input>
      <el-select
          v-model="statusFilter"
          placeholder="订单状态"
          size="small"
          style="width: 100px; margin-left: 8px"
          @change="handleSearch"
      >
        <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.text"
            :value="option.value"
        />
      </el-select>
    </div>

    <div class="order-list" @scroll="handleScroll">
      <el-card
          v-for="order in orders"
          :key="order.id"
          class="order-card"
          shadow="hover"
          :body-style="{ padding: '10px' }"
      >
        <div class="order-header">
          <el-avatar
              :size="32"
              :src="order.buyer.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
          />
          <span class="buyer-name">{{ order.buyer.username }}</span>
          <el-tag :type="getStatusTagType(order.status)" class="status-tag" size="small">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <div class="order-content">
          <el-image
              style="width: 70px; height: 70px; flex-shrink: 0"
              :src="order.product.image || 'https://img.yzcdn.cn/vant/ipad.jpeg'"
              fit="cover"
          />
          <div class="product-info">
            <h4>{{ order.product.title }}</h4>
            <p class="price">¥{{ order.amount.toFixed(2) }}</p>
          </div>
        </div>

        <div class="order-footer">
          <!-- 已付款状态 - 添加标记发货按钮 -->
          <el-button
              v-if="order.status === 1"
              size="small"
              type="primary"
              @click="markAsShipped(order)"
              style="margin-right: 8px"
          >
            标记发货
          </el-button>

          <el-button size="small" @click="showOrderDetail(order)">
            查看详情
          </el-button>
        </div>
      </el-card>

      <div v-if="loading" class="loading-more">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>
      <div v-if="finished" class="no-more">没有更多了</div>
      <div v-if="error" class="error-message">加载失败，请重试</div>
    </div>
    <!-- 订单详情抽屉 -->
    <OrderDetail
        :visible="detailVisible"
        @update:visible="detailVisible = $event"
        :order="selectedOrder"
    />
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, inject} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import OrderDetail from '../components/Order/OrderDetail.vue';
import axios from 'axios';
import router from "@/router";

const detailVisible = ref(false);
const selectedOrder = ref(null);
const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
const orders = ref([]);
const loading = ref(false);
const finished = ref(false);
const error = ref(false);
const searchQuery = ref('');
const statusFilter = ref(-1); // -1表示全部状态
const currentPage = ref(1);
const pageSize = 10;

const statusOptions = [
  { text: '全部状态', value: -1 },
  { text: '待付款', value: 0 },
  { text: '已付款', value: 1 },
  { text: '已发货', value: 2 },
  { text: '已完成', value: 3 },
  { text: '已取消', value: 4 },
];

const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '已付款',
    2: '已发货',
    3: '已完成',
    4: '已取消',
  };
  return statusMap[status] || '未知状态';
};

const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'success',
    4: 'danger',
  };
  return typeMap[status] || '';
};

// 添加返回方法
const handleBack = () => {
  router.go(-1); // 返回上一页
};

// 标记订单为已发货
const markAsShipped = async (order) => {
  try {
    await ElMessageBox.confirm('确认订单已发货？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await axios.post('/backend/order/update', {
      id: order.id,
      status: 2 // 已发货状态
    });

    if (response.data.code === 200) {
      ElMessage.success('订单状态已更新为已发货');
      // 刷新订单列表
      currentPage.value = 1;
      await fetchOrders();
    } else {
      throw new Error(response.data.message || '更新订单状态失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      console.error('标记发货出错:', err);
      ElMessage.error(err.message || '操作失败');
    }
  }
};

const fetchOrders = async () => {
  if (finished.value || loading.value) return;

  try {
    loading.value = true;
    error.value = false;

    const params = {
      sellerId: user.value.userid,
      pageNum: currentPage.value,
      pageSize: pageSize,
    };

    if (searchQuery.value) {
      params.productTitle = searchQuery.value;
    }

    if (statusFilter.value !== -1) {
      params.status = statusFilter.value;
    }

    const response = await axios.get('/backend/order/query', { params });

    if (response.data.code === 200) {
      const data = response.data.data;
      if (currentPage.value === 1) {
        orders.value = data.list;
      } else {
        orders.value = [...orders.value, ...data.list];
      }

      currentPage.value++;
      finished.value = currentPage.value > data.totalPages || data.list.length < pageSize;
    } else {
      throw new Error('获取订单失败');
    }
  } catch (err) {
    console.error('获取订单出错:', err);
    error.value = true;
    ElMessage.error('获取订单出错');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  finished.value = false;
  orders.value = [];
  fetchOrders();
};

const handleScroll = (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target;
  // 当滚动到距离底部50px时加载更多
  if (scrollHeight - (scrollTop + clientHeight) < 50) {
    fetchOrders();
  }
};

const showOrderDetail = (order) => {
  selectedOrder.value = order;
  detailVisible.value = true;
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-container {
  padding: 8px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 0 4px;
}

.order-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
}

.order-card {
  margin-bottom: 8px;
}

.order-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.buyer-name {
  margin-left: 8px;
  flex: 1;
  font-size: 13px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-tag {
  margin-left: 8px;
  flex-shrink: 0;
}

.order-content {
  display: flex;
  margin-bottom: 8px;
  gap: 8px;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-info h4 {
  margin: 0 0 6px 0;
  font-size: 13px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.price {
  margin: 0;
  font-size: 15px;
  color: #f56c6c;
  font-weight: bold;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 4px;
}

.loading-more,
.no-more,
.error-message {
  text-align: center;
  padding: 8px;
  color: #999;
  font-size: 13px;
}

.loading-more .el-icon {
  margin-right: 4px;
  animation: rotating 2s linear infinite;
}

.error-message {
  color: #f56c6c;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式调整 */
@media (max-width: 375px) {
  .search-bar {
    flex-wrap: wrap;
    gap: 6px;
  }

  .search-bar .el-input {
    flex: 1;
    min-width: 0;
  }

  .search-bar .el-select {
    width: 100%;
    margin-left: 0;
  }

  .order-content {
    flex-direction: column;
  }

  .product-info h4 {
    -webkit-line-clamp: 1;
  }
}
</style>